/**
 * Software License, Version 1.0
 * 
 * Copyright 2003 The Trustees of Indiana University.  All rights reserved.
 * 
 *
 *Redistribution and use in source and binary forms, with or without 
 *modification, are permitted provided that the following conditions are met:
 *
 *1) All redistributions of source code must retain the above copyright notice,
 * the list of authors in the original source code, this list of conditions and
 * the disclaimer listed in this license;
 *2) All redistributions in binary form must reproduce the above copyright 
 * notice, this list of conditions and the disclaimer listed in this license in
 * the documentation and/or other materials provided with the distribution;
 *3) Any documentation included with all redistributions must include the 
 * following acknowledgement:
 *
 *"This product includes software developed by the Community Grids Lab. For 
 * further information contact the Community Grids Lab at 
 * http://communitygrids.iu.edu/."
 *
 * Alternatively, this acknowledgement may appear in the software itself, and 
 * wherever such third-party acknowledgments normally appear.
 * 
 *4) The name Indiana University or Community Grids Lab or NaradaBrokering, 
 * shall not be used to endorse or promote products derived from this software 
 * without prior written permission from Indiana University.  For written 
 * permission, please contact the Advanced Research and Technology Institute 
 * ("ARTI") at 351 West 10th Street, Indianapolis, Indiana 46202.
 *5) Products derived from this software may not be called NaradaBrokering, 
 * nor may Indiana University or Community Grids Lab or NaradaBrokering appear
 * in their name, without prior written permission of ARTI.
 * 
 *
 * Indiana University provides no reassurances that the source code provided 
 * does not infringe the patent or any other intellectual property rights of 
 * any other entity.  Indiana University disclaims any liability to any 
 * recipient for claims brought by any other entity based on infringement of 
 * intellectual property rights or otherwise.  
 *
 *LICENSEE UNDERSTANDS THAT SOFTWARE IS PROVIDED "AS IS" FOR WHICH NO 
 *WARRANTIES AS TO CAPABILITIES OR ACCURACY ARE MADE. INDIANA UNIVERSITY GIVES
 *NO WARRANTIES AND MAKES NO REPRESENTATION THAT SOFTWARE IS FREE OF 
 *INFRINGEMENT OF THIRD PARTY PATENT, COPYRIGHT, OR OTHER PROPRIETARY RIGHTS. 
 *INDIANA UNIVERSITY MAKES NO WARRANTIES THAT SOFTWARE IS FREE FROM "BUGS", 
 *"VIRUSES", "TROJAN HORSES", "TRAP DOORS", "WORMS", OR OTHER HARMFUL CODE.  
 *LICENSEE ASSUMES THE ENTIRE RISK AS TO THE PERFORMANCE OF SOFTWARE AND/OR 
 *ASSOCIATED MATERIALS, AND TO THE PERFORMANCE AND VALIDITY OF INFORMATION 
 *GENERATED USING SOFTWARE.
 */
package cgl.narada.wsinfra.wsrm.impl;

import cgl.narada.wsinfra.WsMessageFlow;
import cgl.narada.wsinfra.WsProcessor;
import cgl.narada.wsinfra.exception.DeploymentException;
import cgl.narada.wsinfra.exception.IncorrectExchangeException;
import cgl.narada.wsinfra.exception.MessageFlowException;
import cgl.narada.wsinfra.exception.ProcessingException;
import cgl.narada.wsinfra.exception.UnknownExchangeException;
import cgl.narada.wsinfra.exception.WsFaultException;
import cgl.narada.wsinfra.schemas.addressing.EndpointReferenceType;
import cgl.narada.wsinfra.schemas.soap.EnvelopeDocument;
import cgl.narada.wsinfra.schemas.wsrm.AckRequestedDocument;
import cgl.narada.wsinfra.schemas.wsrm.CreateSequenceDocument;
import cgl.narada.wsinfra.schemas.wsrm.CreateSequenceResponseDocument;
import cgl.narada.wsinfra.schemas.wsrm.SequenceAcknowledgementDocument;
import cgl.narada.wsinfra.schemas.wsrm.SequenceDocument;
import cgl.narada.wsinfra.schemas.wsrm.TerminateSequenceDocument;
import cgl.narada.wsinfra.wsa.AddressingHeaders;
import cgl.narada.wsinfra.wsa.ParseWsaHeaders;
import cgl.narada.wsinfra.wsa.WsaFaultRules;
import cgl.narada.wsinfra.wsa.WsaProcessingFactory;
import cgl.narada.wsinfra.wsrm.WsrmAckOperations;
import cgl.narada.wsinfra.wsrm.WsrmElementAddition;
import cgl.narada.wsinfra.wsrm.WsrmElementCreation;
import cgl.narada.wsinfra.wsrm.WsrmExchangeInfo;
import cgl.narada.wsinfra.wsrm.WsrmExchangeInfoCreator;
import cgl.narada.wsinfra.wsrm.WsrmFaults;
import cgl.narada.wsinfra.wsrm.WsrmNodeUtils;
import cgl.narada.wsinfra.wsrm.WsrmProcessingFactory;
import cgl.narada.wsinfra.wsrm.WsrmQNames;
import cgl.narada.wsinfra.wsrm.WsrmRequestCreator;
import cgl.narada.wsinfra.wsrm.WsrmSequencePolicies;
import cgl.narada.wsinfra.wsrm.WsrmSequencePolicyFactory;
import cgl.narada.wsinfra.wsrm.WsrmSink;
import cgl.narada.wsinfra.wsrm.storage.WsrmAuditStorageOperations;
import cgl.narada.wsinfra.wsrm.storage.WsrmPolicyStorageOperations;
import cgl.narada.wsinfra.wsrm.storage.WsrmProtocolStorageOperations;
import cgl.narada.wsinfra.wsrm.storage.WsrmSequenceInfo;
import cgl.narada.wsinfra.wsrm.storage.WsrmSequenceInfoStorageOperations;
import cgl.narada.wsinfra.wsrm.storage.WsrmStorageEventsFactory;
import cgl.narada.wsinfra.wsrm.storage.WsrmStorageException;
import cgl.narada.wsinfra.wsrm.storage.WsrmStorageService;
import cgl.narada.wsinfra.wsrm.storage.WsrmStorageWidget;

/**
    This interfaces outlines the functionality of a WSRM sink.

    @author Shrideep Pallickara
    $Date: 2005/07/29 22:41:30 $
    $Revision: 1.10 $
*/


public class WsrmSinkNode extends WsProcessor implements WsrmSink {
  private EndpointReferenceType sinkEpr;

  private WsrmQNames wsrmQNames;
  private WsrmFaults wsrmFaults;
  private WsrmSequencePolicyFactory wsrmSequencePolicyFactory;  
  private WsrmExchangeInfoCreator wsrmExchangeInfoCreator;
  private WsrmAckOperations wsrmAckOperations;
  private WsrmElementAddition wsrmElementAddition;
  private WsrmElementCreation wsrmElementCreation;
  private WsrmRequestCreator wsrmRequestCreator;
  private WsrmNodeUtils wsrmNodeUtils;

  private WsrmStorageService wsrmStorageService;
  private WsrmProtocolStorageOperations wsrmProtocolOps;
  private WsrmSequenceInfoStorageOperations wsrmSequenceInfoOps;
  private WsrmPolicyStorageOperations wsrmPolicyOps;
  private WsrmAuditStorageOperations wsrmAuditOps;
  private WsrmStorageEventsFactory storageEventsFactory;

  private WsrmSinkNodeHelper sinkNodeHelper;

  private WsaFaultRules wsaFaultRules;
  private ParseWsaHeaders parseWsaHeaders; 

  private WsMessageFlow wsMessageFlow;
  private String moduleName = "WsrmSinkNode: ";
  

  public WsrmSinkNode(String configInfo) throws DeploymentException {
    try {
      wsrmStorageService = WsrmStorageService.getInstance(configInfo);
      wsrmProtocolOps = wsrmStorageService.getWsrmProtocolStorageOperations();
      wsrmSequenceInfoOps = 
	wsrmStorageService.getWsrmSequenceInfoStorageOperations(); 
      wsrmPolicyOps = wsrmStorageService.getWsrmPolicyStorageOperations();
      wsrmAuditOps =  wsrmStorageService.getWsrmAuditStorageOperations();
      
    } catch (WsrmStorageException wsrmStorageException) {
      String reason = moduleName + "Problems initializing storage services"
	+ ", please check the location of the config file [" + configInfo + 
	"] that was provided.\n" + wsrmStorageException.toString();
      throw new DeploymentException(reason);
    }
   
    storageEventsFactory = WsrmStorageEventsFactory.getInstance();
    
    wsrmQNames =  WsrmQNames.getInstance();
    wsrmFaults = WsrmProcessingFactory.getWsrmFaults();
    wsrmSequencePolicyFactory = 
      WsrmProcessingFactory.getWsrmSequencePolicyFactory();  
    wsrmExchangeInfoCreator = 
      WsrmProcessingFactory.getWsrmExchangeInfoCreator();
    wsrmAckOperations = WsrmProcessingFactory.getWsrmAckOperations();
    wsrmElementAddition = WsrmProcessingFactory.getWsrmElementAddition();
    wsrmElementCreation = WsrmProcessingFactory.getWsrmElementCreation();
    wsrmRequestCreator = WsrmProcessingFactory.getWsrmRequestCreator();
    wsrmNodeUtils = WsrmProcessingFactory.getWsrmNodeUtils();

    wsaFaultRules =  WsaProcessingFactory.getWsaFaultRules();
    parseWsaHeaders = WsaProcessingFactory.getParseWsaHeaders();

    sinkNodeHelper = WsrmSinkNodeHelper.getInstance();
    sinkNodeHelper.initialize(wsrmStorageService);
  }
 

  /** Sets the message flow which the processor should use */
  public void setMessageFlow(WsMessageFlow wsMessageFlow) 
    throws DeploymentException {
    this.wsMessageFlow = wsMessageFlow;
    sinkNodeHelper.setMessageFlow(wsMessageFlow);
  }
  
  /** Gets the message flow which the processor should use. */
  public WsMessageFlow getMessageFlow() {
    return wsMessageFlow;
  }


  /** Process the exchange. The argument also indicates the direction in
      which the exchange has actually traversed. */
  public boolean processExchange(EnvelopeDocument envelopeDocument,
				 int direction)
    throws UnknownExchangeException, IncorrectExchangeException,
    ProcessingException, MessageFlowException  {
    
    WsrmExchangeInfo wsrmExchangeInfo =
      wsrmExchangeInfoCreator.createWsrmExchangeInfo(envelopeDocument);
    AddressingHeaders addressingHeaders = 
      wsrmExchangeInfo.getAddressingHeaders();
    
    boolean isFault = isFault(addressingHeaders);
    if (isFault) {
      return true;
    }

    sinkNodeHelper.checkExchangeType(wsrmExchangeInfo, direction);
    
    try {
      /** Only valid exchanges to be processed now remain */
      if (direction == WsMessageFlow.FROM_APPLICATION) {
	/** We will not be processing any messages from the application. */
	return true;
      }
      
      /** From here on every thing else has been received over the network */
      if (wsrmExchangeInfo.isCreateSequence()) {
	processCreateSequence(envelopeDocument, addressingHeaders);
	return false;
      }
      
      if (wsrmExchangeInfo.isTerminateSequence()) {
	processTerminateSequence(envelopeDocument, addressingHeaders);
	return false;
      }

      if (wsrmExchangeInfo.hasSequence()) {
	processWsrmMessageFromSource(envelopeDocument, addressingHeaders);
      }

      if (wsrmExchangeInfo.hasAckRequested() ) {
	processAckRequested(envelopeDocument, addressingHeaders);
      }

    } catch (WsFaultException wsFaultException) {
      EndpointReferenceType faultTo =
	wsaFaultRules.sendFaultTo(addressingHeaders);
      wsFaultException.setFaultTo(faultTo);
      manageFaultException(wsFaultException, direction);
    } catch (WsrmStorageException wsrmStorageException) {
      /** Need to manage storage exception here */
      System.out.println(moduleName + wsrmStorageException.toString() );
    }
    return true;
  }
  


  /** Process CreateSequence received over the network, from the source */
  public void processCreateSequence(EnvelopeDocument envelopeDocument,
				    AddressingHeaders addressingHeaders)
    throws WsFaultException, MessageFlowException, WsrmStorageException,
    ProcessingException {
    
    /** Prepare the response envelope based on the specified addressing
	headers, report problems if there are any. */
    EnvelopeDocument responseDocument =
      sinkNodeHelper.prepareCreateSequenceResponseEnvelope(addressingHeaders);
    
    /** Proceed to issue the envelope document */
    enrouteToNetwork(responseDocument);
  }


  /** Process a CreateSequence request received from the source */
  public CreateSequenceResponseDocument 
  processCreateSequence(CreateSequenceDocument createSequenceDocument) 
    throws WsFaultException, MessageFlowException  {

    return null;
  }
  

  
  /** Process wsrm message received over the network, from the source */
  public void processWsrmMessageFromSource(EnvelopeDocument envelopeDocument,
					   AddressingHeaders addressingHeaders)
    throws WsFaultException, MessageFlowException, WsrmStorageException  {
    System.out.println(moduleName + "Processing WSRM message from Source");
    
    SequenceDocument sequenceDocument = 
      wsrmNodeUtils.getSequenceDocument(envelopeDocument);
    /** Check to see if there are any problems whatsoever within the sequence 
	element. Specifically, check for logic related to the following wsrm 
	sub-elements viz. sequenceIdentifier, messageNumber and lastMessage. */
    WsrmSequenceInfo wsrmSequenceInfo = 
      sinkNodeHelper.checkSequenceElementForProblems(addressingHeaders,
						     sequenceDocument);

    boolean isDuplicate = sinkNodeHelper.checkIfDuplicate(sequenceDocument);
    
    if (!isDuplicate) {
      long messageNumber = 
	sequenceDocument.getSequence().getMessageNumber().longValue();
      storeWsrmMessage(envelopeDocument, wsrmSequenceInfo, messageNumber);
    } else {
      System.out.println(moduleName + "Duplicate message received.");
    }
  }


  /** Store the Envelope document corresponding to the messageNumber
      and sequenceIdentifier onto stable storage .*/
  private void storeWsrmMessage(EnvelopeDocument envelopeDocument,
				WsrmSequenceInfo wsrmSequenceInfo,
				long messageNumber) 
    throws WsrmStorageException {

    WsrmSequencePolicies wsrmSequencePolicies = 
      wsrmSequenceInfo.getWsrmSequencePolicies();
    long acknowledgementInterval = wsrmSequencePolicies.getAcknowledgementInterval().getAcknowledgementInterval().getMilliseconds().longValue();

    String sequenceIdentifier = wsrmSequenceInfo.getSequenceIdentifier();
    
    WsrmStorageWidget wsrmStorageWidget = 
      storageEventsFactory.createWsrmStorageWidget(sequenceIdentifier,
						   messageNumber, false, 
						   acknowledgementInterval,
						   envelopeDocument); 
    wsrmProtocolOps.store(wsrmStorageWidget);

  }



   /** Process AckRequested received over the network, from the source */
  public void processAckRequested(EnvelopeDocument envelopeDocument,
				  AddressingHeaders addressingHeaders)
    throws WsFaultException, MessageFlowException, WsrmStorageException,
    ProcessingException {
    
    AckRequestedDocument ackRequestedDoc =
      wsrmNodeUtils.getAckRequested(envelopeDocument);
    /** Check for any problems that may exist within the [wsrm:AckRequested]
	element. */
     WsrmSequenceInfo wsrmSequenceInfo =
       sinkNodeHelper.checkAckRequestedElementForProblems(addressingHeaders,
							  ackRequestedDoc);
     String sequenceIdentifier = wsrmSequenceInfo.getSequenceIdentifier();
     boolean ackRequested = true;
     
     long[] acknowledgements = 
       wsrmAckOperations.getMessageNumbersToAcknowledge(sequenceIdentifier, 
							ackRequested, 
							wsrmProtocolOps) ;

     if (acknowledgements == null) {
       /** Nothing to acknowledge. Return. */
       System.out.println(moduleName + "Nothing to acknowledge.");
       return;
     }
     
     boolean positiveAcks = true;
     SequenceAcknowledgementDocument sequenceAckDocument =
       wsrmElementCreation.newSequenceAcknowledgement(sequenceIdentifier, 
						      acknowledgements, 
						      positiveAcks); 
     EnvelopeDocument acknowledgementEnvelope =
       sinkNodeHelper.prepareEnvelopeForAcknowledgement(addressingHeaders,
							wsrmSequenceInfo);
     wsrmElementAddition.addSequenceAcknowledgement(acknowledgementEnvelope,
						    sequenceAckDocument);

     /** Proceed to issue the envelope over the network. */
     enrouteToNetwork(acknowledgementEnvelope);
     
     /** Process the acknowledgements and tags the messages to indicate
	 that they have been acknowledged. This needs to be the last step
	 since by the time the call reaches here, the acknowledgement is 
	 already in transit over the network.*/
     wsrmProtocolOps.processAcknowledgementsOnSequence(sequenceIdentifier,
						       acknowledgements);
  }
  

   /** Process TerminateSequence received over the network, from the source */
  public void processTerminateSequence(EnvelopeDocument envelopeDocument,
				       AddressingHeaders addressingHeaders)
    throws WsFaultException, MessageFlowException, WsrmStorageException  {
    
    TerminateSequenceDocument terminateSequenceDocument =
      wsrmNodeUtils.getTerminateSequenceDocument(envelopeDocument);

    /** Check for any problems that may exist within the 
	[wsrm:TerminateSequence] element. */
    WsrmSequenceInfo wsrmSequenceInfo = 
      sinkNodeHelper.
      checkTerminateSequenceElementForProblems(addressingHeaders,
					       terminateSequenceDocument);
    
    /** Once we have reach here, there are no further issues that need to be
	resolved/dealt-with. Proceed to terminate the sequence */
    String terminationReason = "All messages have been acknowledged, and the" +
      " source has issued a termination request";    
    storageEventsFactory.terminateSequence(wsrmSequenceInfo, 
					   terminationReason);
    
    wsrmSequenceInfoOps.storeCreatedSequence(wsrmSequenceInfo);
  }

  
  /** Process the TerminateSequence message received from the source (over 
      the network)*/
  public void 
  processTerminateSequence(TerminateSequenceDocument terminateSequenceDocument)
    throws WsFaultException, MessageFlowException  {
    
    
  }
  
  
  
  /* Retrieves the endpoint reference associated with this node */
  public EndpointReferenceType getEndpointReference() {
    return sinkEpr;
  }
  
  
  /** Retrieves the endpoint reference associated with this node */
  public void setEndpointReference(EndpointReferenceType endpointReference) {
    this.sinkEpr = endpointReference;
    sinkNodeHelper.setEndpointReference(sinkEpr);
  } 

}
